<form class="layui-form" style="display: none;margin: 50px 60px" action="" id="userForm">
    <input type="hidden" name="id" id="hidden-id"/>
    <div class="layui-form-item">
        <label class="layui-form-label" for="username">用户名：</label>
        <div class="layui-input-block">
            <input type="text" name="username" required lay-verify="required" id="username"
                   placeholder="请输入用户名" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label" for="email">邮箱地址：</label>
        <div class="layui-input-inline" style="width: 527px">
            <input type="text" name="email" required lay-verify="email" id="email"
                   placeholder="请输入邮箱地址" autocomplete="off" class="layui-input">
        </div>
        <div class="layui-form-mid layui-word-aux" style="margin-left: 5px" id="email-aux"></div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label" for="authName">社区认证：</label>
        <div class="layui-input-block">
            <input type="text" name="authName" id="authName"
                   placeholder="请输入社区认证" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-inline">
            <label class="layui-form-label" for="province">省份：</label>
            <div class="layui-input-inline">
                <select name="province" id="province" lay-filter="province">
                </select>
            </div>
            <label class="layui-form-label" for="city">城市：</label>
            <div class="layui-input-inline">
                <select name="city" id="city">
                </select>
            </div>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">性别：</label>
        <div class="layui-input-block">
            <input type="radio" name="gender" value="0" title="男">
            <input type="radio" name="gender" value="1" title="女">
            <input type="radio" name="gender" value="-1" title="保密" checked>
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="userForm">立即提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>

<script>
  const provinces = [];
  const cities = [[]];

  let userCity = '---请选择省份--- ---请选择城市---'

  $.getJSON('/provinces.json', function (res) {
    res.provinces.forEach(province => {
      provinces.push(province.provinceName)
      const inner = []
      province.cities.forEach(city => {
        inner.push(city.cityName)
      })
      cities.push(inner)
    })
  })

  function editOrSave(type, userId) {
    if (type === 'edit') {
      $.get('/admin/user/' + userId, function (res) {
        let data = res.data
        $("#hidden-id").val(data.id)
        $("#username").val(data.username).addClass('layui-disabled').prop('disabled', true)
        $("#email").val(data.email)
        if (data.status === -1) {
          $("#email-aux").html('用户邮箱未激活')
        } else if (data.status > -1) {
          $("#email-aux").html('用户邮箱已激活')
        }
        $("#authName").val(data.authName)
        $("input[name='gender']").each(function () {
          if ($(this).val() === data.gender) {
            $(this).prop('checked', true)
          }
        })
        //重新渲染
        layui.use('form', function () {
          let strings = data.city.split(' ');
          if (strings.length === 2) {
            $("#province").val(strings[0])
            layui.form.render("select");
            $('select[name="province"]').siblings("div.layui-form-select").find('dl dd[lay-value=' + strings[0] + ']').click();
            $("#city").val(strings[1])
            layui.form.render("select");
          }
          layui.form.render();
        });
        openForm()
      })
    } else if (type === 'add') {
      openForm()
    }
  }

  function openForm() {
    layui.use('layer', function () {
      var layer = layui.layer;

      layer.open({
        type: 1,
        area: ['900px', '600px'],
        content: $('#userForm'),
        cancel: function (index, layero) {
          $("button[type='reset']").click()
        }
      });
    })
  }

  function refresh(index) {
    setTimeout(function () {
      $('select[name="province"]').siblings("div.layui-form-select").find('dl dd[lay-value=' + index + ']').click();
    }, 100)
  }

  //Demo
  layui.use(['form', 'layer'], function () {
    var form = layui.form;
    var layer = layui.layer;

    let pi = 1
    let $province = $("#province");
    $province.empty()
    $province.append(new Option('--- 请选择省份 ---', '0'));
    provinces.forEach(p => {
      if (p === userCity[0]) {
        pi = p;
      }
      $province.append(new Option(p, p, p === userCity[0], p === userCity[0]));
    })
    layui.form.render("select");

    form.on('select(province)', function () {
      let index = $(this).index();
      let $city = $("#city");
      $city.empty()
      $city.append(new Option('--- 请选择城市 ---', '0'));
      cities[index].forEach(c => {
        $city.append(new Option(c, c, c === userCity[1], c === userCity[1]));
      })
      layui.form.render("select");
    })

    //监听提交
    form.on('submit(userForm)', function (data) {
      console.log(data.field)
      $.post('/admin/user/set', data.field, function (res) {
        layer.msg(res.msg)
        if (res.status === 0) {
          location.reload()
        }
      })
      return false;
    });

    $(function () {

      $("button[type='reset']").click(function () {
        $("#city").empty()
      })

      refresh(pi)
    })
  });
</script>
